package com.cetool.autocms.aspect;

import cn.hutool.json.JSONUtil;
import com.auth0.jwt.JWT;
import com.cetool.autocms.enumeration.SystemExceptionEnum;
import com.cetool.autocms.exception.ServiceException;
import com.cetool.autocms.pojo.domain.login.UserInfoDO;
import com.cetool.autocms.util.TokenUtil;
import com.cetool.autocms.util.UserInfoContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * token切面
 *
 * @author 戴越
 * @date 2021/11/9
 */
@Component
@Slf4j
@Aspect
public class TokenAspect {
    /**
     * token标识
     */
    private static final String TOKEN = "token";

    /**
     * 定义token切入点
     */
    @Pointcut("@annotation(com.cetool.autocms.annotation.TokenAnnotation)")
    public void tokenPointcut() {
        //自定义token切入点
    }

    @Before("tokenPointcut()")
    public void doBeforeAdvice() {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String token = request.getHeader(TOKEN);
        if (token == null || "".equals(token)) {
            throw new ServiceException(SystemExceptionEnum.USER_TOKEN_EXCEPTION);
        }
        //校验token
        TokenUtil.verifyToken(token);
        //根据token获取登陆用户信息
        UserInfoContextUtil.setUser(JSONUtil.toBean(JWT.decode(token).getClaim("data").asString(), UserInfoDO.class));
    }

    @After("tokenPointcut()")
    public void doAfterAdvice() {
        UserInfoContextUtil.clear();
    }

    @AfterThrowing("tokenPointcut()")
    public void doAfterThrowing() {
        UserInfoContextUtil.clear();
    }

}
